package com.bobbygu.bobbyapp.base;

import com.bobbygu.libnet.exception.ServerException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import retrofit2.HttpException;

/**
 * Created by 顾博君 on 2017/10/19.
 */

public abstract class ErrorConsumer implements Consumer<Throwable> {
    //对应HTTP的状态码
//    private static final int SUCCESS = 200;
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    public static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    @Override
    public void accept(@NonNull Throwable e) throws Exception {
        e.printStackTrace();
        //网络
        if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
//            onError("网络连接超时", String.valueOf(REQUEST_TIMEOUT));
            onError("TIP_NO_NETWORK", String.valueOf(REQUEST_TIMEOUT));
        } else if (e instanceof HttpException) {
            onError("TIP_SERVER_NOT_WORK", String.valueOf(((HttpException) e).code()));
        }
        //服务器
        else if (e instanceof ServerException) {
            onError(e.getMessage(), "null");
        }
        //其它
        else {
            onError("TIP_NO_NETWORK", String.valueOf(REQUEST_TIMEOUT));
        }
    }

    /**
     * 错误回调
     */
    protected abstract void onError(String errMsg, String errCode);

}
